//
//  SetHeaderImageViewController.m
//  XinKaiFa55like
//
//  Created by 55like on 2017/9/22.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "SetHeaderImageViewController.h"
#import "LFImagePickerController.h"
#import <Photos/PHAssetChangeRequest.h>


@interface SetHeaderImageViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,LFImagePickerControllerDelegate>

@property (nonatomic,strong)UIImageView * headerImage;

@property (nonatomic,strong)UIImage * image;

@property (nonatomic,copy)void(^block)();

@end

@implementation SetHeaderImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.block = self.userInfo[@"block"];
    
    [self rightButton:nil image:@"xkf_shareicon" sel:@selector(setImage)];
    
    self.navleftButton = [self leftButton:@"个人资料" image:@"headreturn" sel:@selector(backButtonClicked:)];
    [self updateButtonSatatus:self.navleftButton];
    
    
    self.headerImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20+64, kScreenWidth, kScreenWidth)];
    [self.headerImage imageWithURL:[self.userInfo valueForJSONStrKey:@"path"] defaultImage:@"xkf_txmr"];
    [self.view addSubview:self.headerImage];
    
    
}
-(void)save{
    
    
    krequestParam
    NSMutableArray *fileData = [[NSMutableArray alloc] init];
    
    
    
    for (int i = 0; i < 1; i++) {
        
        UIImage *image = self.image;
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation([[Utility Share]imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)], 1),@"fileData",@"icon",@"fileKey",@"aa.jpg",@"fileName",@"image",@"fileType", nil];
        
        
        [fileData addObject:dic];
    }
    
    
    [NetEngine uploadAllFileAction:@"user/profiles" withParams:dictparam fileArray:fileData onCompletion:^(id resData, BOOL isCache) {
        
        
        [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        
        
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            
            
            self.headerImage.image = self.image;
            
            if (self.block) {
                self.block();
            }
            
            
        }else{
            
            
            
            
            
            
            
        }
        
        
        
        
    } onError:^(NSError *error) {
        
        
        [SVProgressHUD showErrorWithStatus:@"请检查网络连接~"];
        
        
        
    } withMask:SVProgressHUDMaskTypeClear];
    
    
    
}
-(void)updateButtonSatatus:(UIButton *)btnT{
    CGSize imageSize = btnT.imageView.frame.size;
    CGSize titleSize = btnT.titleLabel.frame.size;
    CGSize textSize = [btnT.titleLabel sizeThatFits:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + 2);
    btnT.imageEdgeInsets = UIEdgeInsetsMake((totalHeight - imageSize.height)/2, 10.0, (totalHeight - imageSize.height)/2, - titleSize.width);
    btnT.titleEdgeInsets = UIEdgeInsetsMake((totalHeight - imageSize.height)/2,  imageSize.width + 6, (totalHeight - imageSize.height)/2, 0);
}
-(void)setImage{
    
    
    EMWeakSelf(weakSelf);
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        [QSheetQAlertView showQSheetQAlertViewWithTitleArray:@[@"拍照",@"从手机相册选择",@"保存图片"] cellClickIndex:^(NSInteger index) {
            
            if (index == 0) {
                
                UIImagePickerController *imagepic = [[UIImagePickerController alloc]init];
                imagepic.delegate = weakSelf;
                imagepic.allowsEditing = YES;
                imagepic.sourceType  = UIImagePickerControllerSourceTypeCamera;
                [weakSelf presentViewController:imagepic animated:YES completion:nil];
                
            }else if (index == 1){
                
                LFImagePickerController *imagePicker = [[LFImagePickerController alloc] initWithMaxImagesCount:10 delegate:weakSelf];
                imagePicker.allowTakePicture = NO;
                imagePicker.allowPickingVideo = NO;
                imagePicker.doneBtnTitleStr = @"完成";
                imagePicker.allowEditting = NO;
                imagePicker.allowPickingOriginalPhoto=YES;
                imagePicker.showRadioImage=YES;
                imagePicker.cropImageSize=CGSizeMake(kScreenWidth*1.5, kScreenWidth*1.5);
                
                [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                
                
            }else{
                
                
                [weakSelf loadImageFinished:weakSelf.headerImage.image];
                
            }
            
            
        }];
        
    }else{
        
        [QSheetQAlertView showQSheetQAlertViewWithTitleArray:@[@"从手机相册选择",@"保存图片"] cellClickIndex:^(NSInteger index) {
            
            if (index == 0){
                
                LFImagePickerController *imagePicker = [[LFImagePickerController alloc] initWithMaxImagesCount:10 delegate:weakSelf];
                imagePicker.allowTakePicture = NO;
                imagePicker.allowPickingVideo = NO;
                imagePicker.doneBtnTitleStr = @"完成";
                imagePicker.allowEditting = NO;
                imagePicker.allowPickingOriginalPhoto=YES;
                imagePicker.showRadioImage=YES;
                imagePicker.cropImageSize=CGSizeMake(kScreenWidth*1.5, kScreenWidth*1.5);
                
                [weakSelf presentViewController:imagePicker animated:YES completion:nil];
                
                
            }else{
                
                
                [weakSelf loadImageFinished:weakSelf.headerImage.image];
                
            }
            
            
        }];
        
        
    }
    
    
    
  
    
    
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    self.image = image;
    [self save];
    
    [self dismissViewControllerAnimated:YES completion:^{
       
    }];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}
#pragma mark LFImagePickerControllerDelegate

- (void)lf_imagePickerController:(LFImagePickerController *)picker didFinishPickingRadioCropImages:(UIImage *)cropImage originalImages:(UIImage *)originalImage{
    
    
    self.image = cropImage;
    
    [self save];
    
    
}
- (void)loadImageFinished:(UIImage *)image
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        //写入图片到相册
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (!error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [SVProgressHUD showImage:nil status:@"已保存到本地相册"];
            });
            
        }
        
        
        NSLog(@"success = %d, error = %@", success, error);
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
